<template>
  <div class="app-container">
    <!-- 提示信息 -->
    <el-alert
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;"
    >
      <template slot="title">
        <strong>📋 志愿变更说明</strong>
      </template>
      <div style="font-size: 13px; line-height: 1.8; color: #606266;">
        • <strong>变更条件</strong>：您必须已被某个题目录取后才能申请换题<br/>
        • <strong>审核流程</strong>：同一教师内换题只需教师审核一次；跨教师换题需要原教师和新教师都同意<br/>
        • <strong>注意事项</strong>：在有待审核的变更申请时，不能提交新的变更申请<br/>
        • <strong>变更影响</strong>：变更成功后，原题目将被释放，您将被分配到新题目
      </div>
    </el-alert>

    <!-- 操作按钮 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="24">
        <el-button
          type="primary"
          icon="el-icon-edit"
          @click="handleSubmit"
          :disabled="!canSubmit"
        >
          申请换题
        </el-button>
        <el-button
          icon="el-icon-refresh"
          @click="getList"
        >
          刷新
        </el-button>
        <span v-if="!canSubmit" style="color: #F56C6C; margin-left: 10px;">
          <i class="el-icon-warning"></i>
          {{ canSubmitMessage }}
        </span>
      </el-col>
    </el-row>

    <!-- 申请列表 -->
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span class="card-title">我的换题申请</span>
      </div>

      <el-table v-loading="loading" :data="requestList" border>
        <el-table-column label="序号" type="index" width="50" align="center" />
        
        <el-table-column label="原题目" min-width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <div><strong>{{ scope.row.oldTopicTitle }}</strong></div>
            <div style="color: #909399; font-size: 12px;">原教师: {{ scope.row.oldTeacherName }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="新题目" min-width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <div><strong>{{ scope.row.newTopicTitle }}</strong></div>
            <div style="color: #909399; font-size: 12px;">新教师: {{ scope.row.newTeacherName }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="变更类型" width="110" align="center">
          <template slot-scope="scope">
            <el-tag :type="isSameTeacher(scope.row) ? 'info' : 'primary'" size="small">
              {{ isSameTeacher(scope.row) ? '同教师内' : '跨教师' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="审核进度" min-width="200" align="center">
          <template slot-scope="scope">
            <!-- 同一教师：只显示一个状态 -->
            <div v-if="isSameTeacher(scope.row)" style="text-align: center;">
              <el-tag 
                :type="scope.row.oldTeacherOpinion === '同意' ? 'success' : scope.row.oldTeacherOpinion === '拒绝' ? 'danger' : 'warning'"
                size="medium"
              >
                <i :class="getStepIcon(scope.row.oldTeacherOpinion)"></i>
                {{ getStepDesc(scope.row.oldTeacherOpinion) }}
              </el-tag>
            </div>
            <!-- 不同教师：显示两个步骤 -->
            <el-steps v-else :active="getStepActive(scope.row)" simple>
              <el-step 
                title="原教师" 
                :icon="getStepIcon(scope.row.oldTeacherOpinion)"
                :status="getStepStatus(scope.row.oldTeacherOpinion)"
              ></el-step>
              <el-step 
                title="新教师" 
                :icon="getStepIcon(scope.row.newTeacherOpinion)"
                :status="getStepStatus(scope.row.newTeacherOpinion)"
              ></el-step>
            </el-steps>
          </template>
        </el-table-column>
        
        <el-table-column label="最终状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.finalStatus || scope.row.status)" size="small">
              {{ scope.row.finalStatus || scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="申请时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >详情</el-button>
            <el-button
              v-if="scope.row.status === '待审核'"
              size="mini"
              type="text"
              icon="el-icon-close"
              @click="handleCancel(scope.row)"
              style="color: #F56C6C;"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="requestList.length === 0" style="text-align: center; padding: 40px; color: #909399;">
        <i class="el-icon-info" style="font-size: 48px;"></i>
        <p style="margin-top: 10px;">暂无换题申请记录</p>
      </div>
    </el-card>

    <!-- 提交申请对话框 -->
    <submit-dialog ref="submitDialog" @success="getList" />

    <!-- 详情对话框 -->
    <detail-dialog ref="detailDialog" />
  </div>
</template>

<script>
import { listMyChangeRequests, cancelChangeRequest, checkCanSubmit } from "@/api/system/topicChangeRequest";
import SubmitDialog from "./SubmitDialog";
import DetailDialog from "./DetailDialog";

export default {
  name: "StudentChangeRequest",
  components: {
    SubmitDialog,
    DetailDialog
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 申请列表
      requestList: [],
      // 是否可以提交申请
      canSubmit: false,
      // 不能提交的原因
      canSubmitMessage: ''
    };
  },
  created() {
    this.getList();
    this.checkSubmitStatus();
  },
  methods: {
    /** 查询申请列表 */
    getList() {
      this.loading = true;
      listMyChangeRequests().then(response => {
        this.requestList = response.data;
        this.loading = false;
      });
    },
    /** 检查是否可以提交申请 */
    checkSubmitStatus() {
      checkCanSubmit().then(response => {
        this.canSubmit = response.data;
        if (!this.canSubmit) {
          // 检查具体原因
          if (this.requestList.some(r => r.status === '待审核')) {
            this.canSubmitMessage = '您有待审核的申请，请等待审核完成';
          } else {
            this.canSubmitMessage = '您还未被任何题目录取';
          }
        }
      });
    },
    /** 提交申请 */
    handleSubmit() {
      this.$refs.submitDialog.open();
    },
    /** 查看详情 */
    handleView(row) {
      this.$refs.detailDialog.open(row.requestId);
    },
    /** 取消申请 */
    handleCancel(row) {
      this.$confirm('是否确认取消该换题申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return cancelChangeRequest(row.requestId);
      }).then(() => {
        this.$modal.msgSuccess("取消成功");
        this.getList();
        this.checkSubmitStatus();
      }).catch(() => {});
    },
    /** 判断是否是同一个教师 */
    isSameTeacher(row) {
      return row.oldTeacherId === row.newTeacherId;
    },
    /** 获取步骤激活状态 */
    getStepActive(row) {
      if (row.finalStatus === '已通过') return 2;
      if (row.finalStatus === '已拒绝') return row.newTeacherOpinion ? 2 : 1;
      if (row.newTeacherOpinion) return 2;
      if (row.oldTeacherOpinion) return 1;
      return 0;
    },
    /** 获取步骤图标 */
    getStepIcon(opinion) {
      if (opinion === '同意') return 'el-icon-check';
      if (opinion === '拒绝') return 'el-icon-close';
      return 'el-icon-time';
    },
    /** 获取步骤状态 */
    getStepStatus(opinion) {
      if (opinion === '同意') return 'success';
      if (opinion === '拒绝') return 'error';
      return 'wait';
    },
    /** 获取步骤描述（用于同一教师的情况） */
    getStepDesc(opinion) {
      if (opinion === '同意') return '教师已同意';
      if (opinion === '拒绝') return '教师已拒绝';
      return '待教师审核';
    },
    /** 状态标签类型 */
    getStatusType(status) {
      const map = {
        '待审核': 'warning',
        '已通过': 'success',
        '已拒绝': 'danger',
        '已取消': 'info'
      };
      return map[status] || 'info';
    }
  }
};
</script>

<style scoped lang="scss">
.card-title {
  font-size: 16px;
  font-weight: bold;
}

::v-deep .el-steps--simple {
  padding: 0;
  background: transparent;
}
</style>